package com.iasku.iaskueleclass_phone.activity;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.iasku.constant.Constant;
import com.iasku.constant.IntentConfig;
import com.iasku.entity.IaskuExam;
import com.iasku.entity.IaskuQuestion;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.manager.DataManager;
import com.iasku.manager.IDataManager;
import com.iasku.util.BaseUtil;

/**
 * 已提交作业
 * 或
 * 已批改作业
 */
public class HomeworkSubmitActivity extends BaseActivity {
    private static final int TASK_GET_EAXM = 1;
    private static final int TASK_GET_ANSWER = 2;
    private static final int TASK_GET_QUESTIONBYID = 3;
    private static final int TASK_SUBMIT_USERANSWER = 4;

    private String examid;
    private TextView mQuesInfoTv;
    private WebView mQuesWv;
    private RadioGroup mRadioGroup;
    private RadioButton mTrueBtn, mFalseBtn;
    private LinearLayout mQueChooseLayout;
    private ImageView mPrevBtn, mNextBtn;
    private IaskuExam mIaskuExam;
    private List<IaskuQuestion> mQuestions;
    private int mQuestionIndex;
    private IaskuQuestion mIQuestion;
    private CheckBox[] mChoice;
    private ImageView mCheckIv;
    private LinearLayout mAnswerBtn, mSubmitBtn;
    private LinearLayout mLayoutBottom;
    private int screenWidth;

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mQuesWv = (WebView) findViewById(R.id.wv_work_question);
        mQuesWv.getSettings().setJavaScriptEnabled(true);
        mQuesWv.getSettings().setSupportZoom(true);
        mQuesWv.getSettings().setBuiltInZoomControls(true);
        mQuesWv.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                mProgressDialog.dismiss();
                mQuesWv.setVisibility(View.VISIBLE);
                setButtonStatus();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    private void setupView() {
        mQuesInfoTv = (TextView) findViewById(R.id.tv_work_question_info);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_work_question);
        mQueChooseLayout = (LinearLayout) findViewById(R.id.layout_choose);
        mPrevBtn = (ImageView) findViewById(R.id.previous_question_iv);
        mNextBtn = (ImageView) findViewById(R.id.next_question_iv);
        mTrueBtn = (RadioButton) findViewById(R.id.rb_work_question_right);
        mFalseBtn = (RadioButton) findViewById(R.id.rb_work_question_wrong);
        mAnswerBtn = (LinearLayout) findViewById(R.id.btn_work_question_answer);
        mSubmitBtn = (LinearLayout) findViewById(R.id.btn_work_question_submit);
        mCheckIv = (ImageView) findViewById(R.id.iv_work_question_check);
        mLayoutBottom = (LinearLayout) findViewById(R.id.layout_question_bottom);
    }

    private void addLister() {
        MyOnClickListener mListener = new MyOnClickListener(this);
        mPrevBtn.setOnClickListener(mListener);
        mNextBtn.setOnClickListener(mListener); 
        mAnswerBtn.setOnClickListener(mListener);
    }

    private void initView() {
        examid = getIntent().getStringExtra(IntentConfig.EXAMID);
        String examname = getIntent().getStringExtra(IntentConfig.EXAMNAME);
        mQuestionIndex = 0;
        initTitleBar(examname);
        setupView();
        initWebView();
        addLister();
        mRadioGroup.setEnabled(false);
        mTrueBtn.setEnabled(false);
        mFalseBtn.setEnabled(false);
        mCheckIv.setVisibility(View.VISIBLE);
        mSubmitBtn.setVisibility(View.GONE);
        mPrevBtn.setVisibility(View.GONE);
        mNextBtn.setVisibility(View.GONE);
        startTask(TASK_GET_EAXM);
    }

    private void setViewValue() {
        setTitleInfo();
        setChoiceValue();
        loadUrl();
    }
    
    private void setTitleInfo(){
        StringBuffer buf = new StringBuffer();
        buf.append("共").append(mQuestions.size()).append("题，第").append(mQuestionIndex + 1).append("题，")
        .append(mIQuestion.getQuestiontype_name())
        .append("，本题").append(mIQuestion.getQuestion_score()).append("分，得")
        .append(mIQuestion.getUserscore()).append("分");
        mQuesInfoTv.setText(buf.toString());
    }

    private void loadUrl() {
        String loadUrl = Constant.SERVERURL + Constant.WEB_LOAD + mIQuestion.getQuestionno() + "&status=0";
        mQuesWv.loadUrl(loadUrl);
    }

    private void checkedImg(){
        mQueChooseLayout.addView(mCheckIv);
        String getscore = mIQuestion.getUserscore();
        String maxscore = mIQuestion.getQuestion_score();
        if("0".equals(getscore)){
            mCheckIv.setImageResource(R.drawable.wrong);
        }else if(getscore.equals(maxscore)){
            mCheckIv.setImageResource(R.drawable.right);
        }else{
            mCheckIv.setImageResource(R.drawable.wrong);
        }
    }
    
    private void checkScore(){
        String getscore = mIQuestion.getUserscore();
        String maxscore = mIQuestion.getQuestion_score();
        if("0".equals(getscore)){
            mQuesInfoTv.setTextColor(Color.RED);
            if(mIQuestion.getAttachStr() != null && !"".equals(mIQuestion.getAttachStr()) && 
                    !"null".equals(mIQuestion.getAttachStr())){
                mQuesInfoTv.setTextColor(getResources().getColor(R.color.work_titleinfo_color));
                mIQuestion.setUserscore("");
                setTitleInfo();
            }
        }else if(getscore.equals(maxscore)){
            mQuesInfoTv.setTextColor(Color.GREEN);
        }else{
            mQuesInfoTv.setTextColor(getResources().getColor(R.color.work_titleinfo_color));
        }
    }
    
    private void setChoiceValue() {
        checkScore();
        final int choiceno = mIQuestion.getChoicenum();
        if (choiceno == 0) {
            if (mIQuestion.getQuestion_type_id() == Constant.TYPE_XUANZ) {
                mQueChooseLayout.removeAllViews();
                if (!"0".equals(mIQuestion.getAnswerid())) {
                    if (mIQuestion.getUseranswer().startsWith("T"))
                        mTrueBtn.setChecked(true);
                    else if (mIQuestion.getUseranswer().startsWith("F")) {
                        mFalseBtn.setChecked(true);
                    } else {
                        mTrueBtn.setChecked(false);
                        mFalseBtn.setChecked(false);
                    }
                } else {
                    mTrueBtn.setChecked(false);
                    mFalseBtn.setChecked(false);
                }
                mQueChooseLayout.addView(mRadioGroup);
                mQueChooseLayout.setVisibility(View.VISIBLE);
                checkedImg();
                mLayoutBottom.setVisibility(View.GONE);
                mAnswerBtn.setVisibility(View.GONE);
            } else {
                mQueChooseLayout.setVisibility(View.GONE);
                mLayoutBottom.setVisibility(View.VISIBLE);
                mAnswerBtn.setVisibility(View.VISIBLE);
            }
        } else {
            mQueChooseLayout.removeAllViews();
            mChoice = new CheckBox[choiceno];
            for (int i = 0; i < choiceno; i++) {
                mChoice[i] = new CheckBox(this);
                mChoice[i].setText("" + (char) (65 + i));
                mChoice[i].setTextColor(getResources().getColor(R.color.modify_text_left));
                mChoice[i].setButtonDrawable(R.drawable.checkbox_uncheck);
                mChoice[i].setId(1000 + i);
                LinearLayout.LayoutParams lout = new LinearLayout.LayoutParams(screenWidth / 6, LayoutParams.WRAP_CONTENT);
                lout.leftMargin = 20;
                lout.gravity = Gravity.CENTER_VERTICAL;
                mChoice[i].setLayoutParams(lout);
                mChoice[i].setGravity(Gravity.CENTER_VERTICAL);
                mChoice[i].setChecked(false);
                mChoice[i].setEnabled(false);
                mQueChooseLayout.addView(mChoice[i]);
            }
            if (!"0".equals(mIQuestion.getAnswerid())) {
                for (int i = 0; i < mIQuestion.getUseranswer().length(); i++) {
                    int ci = (int) mIQuestion.getUseranswer().charAt(i) - 65;
                    if ((ci > -1) && (ci < choiceno)){
                        mChoice[ci].setChecked(true);
                        mChoice[ci].setButtonDrawable(R.drawable.checkbox_checked);
                    }
                        
                }
            }
            checkedImg();
            mQueChooseLayout.setVisibility(View.VISIBLE);
            mLayoutBottom.setVisibility(View.GONE);
            mAnswerBtn.setVisibility(View.GONE);
        }
    }

    private void setButtonStatus() {
        mPrevBtn.setVisibility(View.VISIBLE);
        mNextBtn.setVisibility(View.VISIBLE);
        if (mQuestions.size() == 1) {
            mPrevBtn.setVisibility(View.GONE);
            mNextBtn.setVisibility(View.GONE);
        } else {
            if (mQuestionIndex == 0) {
                mPrevBtn.setVisibility(View.GONE);
            } else if (mQuestionIndex == mQuestions.size() - 1) {
                mNextBtn.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onCreate(Bundle saveInstance) {
        // TODO Auto-generated method stub
        super.onCreate(saveInstance);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        setContentView(R.layout.homework_question_layout);
        initView();
    }

    @Override
    public int onTaskStart(int taskId, Bundle bundle) {
        if (taskId == TASK_GET_ANSWER) {
            mQuesWv.setVisibility(View.INVISIBLE);
            mProgressDialog.show();
        }
        // TODO Auto-generated method stub
        return super.onTaskStart(taskId, bundle);
    }

    @Override
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        switch (taskId) {
        case TASK_GET_EAXM: {
            IDataManager manager = DataManager.getInstance();
            ReturnData<IaskuExam> mReturnData = manager.getExam(this, examid);
            mIaskuExam = mReturnData.getData();
            mQuestions = mIaskuExam.getQuestions();
            return new Status(mReturnData);
        }
        case TASK_GET_ANSWER: {
            mIQuestion = mQuestions.get(mQuestionIndex);
            IDataManager manager = DataManager.getInstance();
            manager.getUserAnswer(Constant.USER_IASKUNAME, mIaskuExam.getExamid(), mIQuestion.getQuestionno(),
                    mIQuestion);
        }
            break;
        case TASK_GET_QUESTIONBYID: {
            IDataManager manager = DataManager.getInstance();
            manager.getQuestionById(mIQuestion);
        }
            break;
        case TASK_SUBMIT_USERANSWER: {
            IDataManager manager = DataManager.getInstance();
            int isright = 0;
            String useranswer = mIQuestion.getUseranswer();
            String trueanswer = mIQuestion.getTrueanswer();
            if (trueanswer.equals(useranswer)) {
                isright = 1;
            } else {
                isright = 0;
            }
            ReturnData<String> mReturnData = manager
                    .submitUserAnswer(Constant.USER_IASKUNAME, mIaskuExam.getExamid(), mIQuestion.getQuestionno(),
                            mIQuestion.getUseranswer(), mIQuestion.getIsattach(), mIQuestion.getQuestion_score(),
                            mIQuestion.getQuestiontype_id(), mIaskuExam.getSubjectid(), isright);
            return new Status(mReturnData);
        }
        }
        return super.onTaskInBackground(taskId, bundle);
    }

    @Override
    public int onTaskComplete(int taskId, Status status) {
        switch (taskId) {
        case TASK_GET_EAXM: {
            if (status.code == 0) {
                startTask(TASK_GET_ANSWER);
            }
        }
            break;
        case TASK_GET_ANSWER: {
            startTask(TASK_GET_QUESTIONBYID);
        }
            break;
        case TASK_GET_QUESTIONBYID: {
            setViewValue();
        }
            break;
        case TASK_SUBMIT_USERANSWER: {
            if (status.code == 0) {
                startTask(TASK_GET_ANSWER);
            }
        }
            break;
        }
        // TODO Auto-generated method stub
        return super.onTaskComplete(taskId, status);
    }

    private class MyOnClickListener implements OnClickListener {
        private Context mContext;
        
        public MyOnClickListener(Context mContext){
            this.mContext = mContext;
        }
        
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.previous_question_iv: // 上一题
                previous();
                break;
            case R.id.next_question_iv: // 下一题
                next();
                break;
            case R.id.btn_work_question_answer: //解答
                answer();
                break;
            }
        }

        private void previous() {
            mQuestionIndex--;
            submitTeacherAnswer();
        }

        private void submitTeacherAnswer() {
            startTask(TASK_GET_ANSWER);
        }

        private void next() {
            mQuestionIndex++;
            submitTeacherAnswer();
        }
        
        private void answer(){
            String attach = mIQuestion.getAttachStr();
            if(attach == null || "".equals(attach) || "null".equals(attach)){
                BaseUtil.showText(mContext,"此题没有解答");
                return;
            }
            Intent intent = new Intent();
            intent.setClass(HomeworkSubmitActivity.this,HomeworkSubmitAnswerActivity.class);
            intent.putExtra(IntentConfig.ANSWER_ATTACH, attach);
            startActivity(intent);
        }
    }
}
